import { Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, Select, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useParams, useHistory } from "react-router-dom";
import "./index.module.scss";
import { getchannelList } from "../../api/channels";

/* 富文本 */
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { useEffect, useState, useRef } from "react";
import { addArticle, editArticle, getArticleDetail } from "@/api/article";
const { Option } = Select;

const Publish = props => {
  /* history路由 */
  const history = useHistory();
  /* 频道 */
  const [channels, setChannels] = useState([]);
  /* 页面加载发送请求获取表格数据进行渲染 */
  useEffect(() => {
    /* 获取频道 */
    const getchannels = async () => {
      try {
        let {
          data: { channels },
        } = await getchannelList();
        setChannels(channels);
      } catch (error) {
        console.log(error);
      }
    };
    getchannels();
  }, []);

  // 使用useRef声明一个暂存仓库
  const cacheImgList = useRef([]);
  /* 上传图片 数据 */
  const [fileList, setFileList] = useState([]);

  /* 上传图片监听 */
  const onUploadChange = ({ fileList }) => {


    
    // 这个函数的执行分阶段 是从updating到done的过程
    setFileList(fileList);
    cacheImgList.current = fileList;
  };
  /* 切换图片 */
  const [imgCount, setImageCount] = useState(1);
  const radioChange = data => {
    const rawValue = data.target.value;
    setImageCount(rawValue);
    // 无图模式
    if (cacheImgList.current.length === 0) {
      return false;
    }
    // 单图模式
    if (rawValue === 1) {
      const img = cacheImgList.current[0];
      setFileList([img]);
      // 多图模式
    } else if (rawValue === 3) {
      setFileList(cacheImgList.current);
    }
  };

  /* 表单提交 */
  const submitHandle = async values => {
    // 数据的二次处理 重点是处理cover字段
    const { channel_id, content, title, type } = values;
    // 判断type fileList 是匹配的才能正常提交
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map(item => item.url),
      },
    };
    if (id) {
      await addArticle(params);
    } else {
      await editArticle(params);
    }
    // 跳转列表 提示用户
    history.push("/home/amin");
    message.success(`${id ? "更新成功" : "发布成功"}`);
  };
  // 编辑功能
  // 拿取路由参数id
  const param = useParams();
  const id = param.id;
  const formRef = useRef();
  // 数据回填
  // 调用接口
  useEffect(() => {
    // 有id的情况下才能发送请求
    // 发送请求
    const ArticleDetail = async () => {
      let { data } = await getArticleDetail(id);
      formRef.current.setFieldsValue({ ...data, type: data.cover.type });
      // 图片回填 回填upload
      const fileList = data.cover.images.map(url => ({ url }));
      setFileList(fileList);
      // 暂存列表里也存一份
      cacheImgList.current = fileList;
      // // 图片type
      // setImageCount(data.cover.type);
    };

    if (id) {
      ArticleDetail();
    }
  }, [id]);
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? "修改文章" : "发布文章"}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* // 注意：此处需要为富文本编辑表示的 content 文章内容设置默认值 */}
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: "" }}
          onFinish={submitHandle}
          ref={formRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: "请选择文章频道" }]}
          >
            {/* <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              <Option value={0}>推荐</Option>
            </Select> */}
            <Select placeholder="请选择文章频道" style={{ width: 200 }}>
              {channels.map(item => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
                multiple={imgCount} //支持是否多张图片上传
                maxCount={imgCount} //限制图片最大数量
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <ReactQuill className="publish-quill" theme="snow" placeholder="请输入文章内容" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id ? "修改文章" : "发布文章"}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
